from mid_project.settings import DEFAULT_AVATAR_PATH
from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework.decorators import  api_view,permission_classes
from rest_framework.permissions import AllowAny
from rest_framework import status
from personal_manage.models import MyUser
from django.contrib.auth.hashers import make_password
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.views import TokenRefreshView
from django.core.files.storage import default_storage
from mid_project import settings
import uuid
import os

@api_view(['POST'])
@permission_classes([AllowAny]) 
def login(request):
    #登录
    print('LOGIN request:', request.method, request.path, request.data)
    _username = request.data.get('username')
    _password = request.data.get('password')
    _email = request.data.get('email')

    if not _username:
        #邮箱登录
        user = MyUser.objects.get(email=_email)
    if not _email:
        #用户名登录
        user = MyUser.objects.get(username=_username)

    if not user.check_password(_password):
        data = {
            "error":"用户名或密码错误",
            "code":"401"
        }
        return JsonResponse(data,status=401)
    else:
        refresh = RefreshToken.for_user(user)
        access_token = refresh.access_token
        level = 1 if user.is_staff else 0
        data = {
            'access': str(access_token),
            'refresh': str(refresh),
            'user': {
                'uid': user.id,
                'username': user.username,
                'email': user.email,
                'avatar': user.avatar,
                'level': level
            }
        }
        return JsonResponse(data, status=status.HTTP_200_OK)

@api_view(['POST'])
@permission_classes([AllowAny]) 
def register(request):
    #注册
    print('REGISTER request:', request.method, request.path, request.data)
    _username = request.data.get('username')
    _raw_password = request.data.get('password')
    _email = request.data.get('email')
    
    hash_password = make_password(_raw_password)

    new_user = MyUser(username=_username, password=hash_password, email=_email, avatar=DEFAULT_AVATAR_PATH)

    try:
        new_user.save()
    except Exception as e:
        data = {
            "error":str(e),
            "code":"400"
        }
        return JsonResponse(data,status=400)
    
    refresh = RefreshToken.for_user(new_user)
    access_token = refresh.access_token
    newuid = MyUser.objects.get(username=_username, email=_email).id
    level = 1 if new_user.is_staff else 0
    data = {
        'access': str(access_token),
        'refresh': str(refresh),
        'user': {
            'uid': newuid,
            'username': _username,
            'email': _email,
            'avatar': DEFAULT_AVATAR_PATH,
            'level': level
        }
    }
    return JsonResponse(data, status=status.HTTP_201_CREATED)

@api_view(['POST'])
@permission_classes([AllowAny]) 
def logout(request):
    #登出
    return JsonResponse({ "message": "登出成功"}, status=status.HTTP_200_OK)

class MyTokenRefreshView(TokenRefreshView):
    permission_classes = [AllowAny]

@api_view(['POST'])
def updata_avatar(request):
    #更新头像
    print('UPDATA_AVATAR request:', request.method, request.path, request.FILES, request.POST)
    
    try:
        user = request.user
        new_avatar = request.FILES.get('avatar')

        #uuid文件名
        ext = os.path.splitext(new_avatar.name)[1]
        unique_filename = f"{uuid.uuid4().hex}{ext}"
        #存储路径/media/images/avatar/{unique_filename}
        save_directory = os.path.join(settings.MEDIA_ROOT, 'images','avatar')
        full_file_path = os.path.join(save_directory, unique_filename)

        #存储
        save_path = default_storage.save(full_file_path, new_avatar)
        #更新前保存原头像路径
        ori_avatar_path = user.avatar
        #更新用户头像路径
        user.avatar = save_path
        user.save()
    except Exception as e:
        data = {
            "error": str(e),
            "code": "500"
        }
        return JsonResponse(data, status=500)
    
    #删除原头像文件
    if os.path.isfile(ori_avatar_path) and ori_avatar_path != DEFAULT_AVATAR_PATH:
        os.remove(ori_avatar_path)
    else:
        print("原头像文件不存在，或为默认头像，未删除。")

    data = {
        "avatar": save_path
    }
    return JsonResponse(data, status=status.HTTP_200_OK)

@api_view(['GET'])
@permission_classes([AllowAny]) 
def get_user_avatar(request, id):
    #获取用户头像

    try:
        user = MyUser.objects.get(id=id)
        avatar_path = user.avatar
    except MyUser.DoesNotExist:
        data = {
            "error": "用户不存在",
            "code": "404"
        }
        return JsonResponse(data, status=404)

    data = {
        "avatar": avatar_path
    }
    return JsonResponse(data, status=200)
